package cn.edu.jxau.test;

/**
 * 找到和顶点start连通的所有顶点
 * 核心是DFS
 * 
 * @author 付大石
 */
public class Search {

    public static void main(String[] args) {

        Graph g = new UndirectedGraph(13);
        g.addEdge(0, 5);
        g.addEdge(4, 3);
        g.addEdge(0, 1);
        g.addEdge(9, 12);
        g.addEdge(6, 4);
        g.addEdge(5, 4);
        g.addEdge(0, 2);
        g.addEdge(11, 12);
        g.addEdge(9, 10);
        g.addEdge(0, 6);
        g.addEdge(7, 8);
        g.addEdge(9, 11);
        g.addEdge(5, 3);
//        g.addEdge(6, 7); 增加这两个边后会变成连通图
//        g.addEdge(8, 9);
        Search search = new Search(g, 0);
//        Search search = new Search(g,9);
        // 打印与对于顶点相连通的顶点 //
        for (int i = 0; i < g.v(); i++) {
            if(search.marked(i)) {
                System.out.print(i+" ");
            }
        }
        System.out.println();
        if(search.count() == g.v()) {
            System.out.println("这是一个连通图");
        } else {
            System.out.println("这不是一个连通图");
        }
    }

    private boolean[] marked;
    private int count;

    public Search(Graph g, int start) {
        marked = new boolean[g.v()];
        dfs(g, start);
    }

    private void dfs(Graph g, int v) {

        marked[v] = true;
        count++;
        for (int i : g.adj(v)) {
            if (!marked[i]) {
                dfs(g, i);
            }
        }
    }

    public boolean marked(int v) {
        return marked[v];
    }

    public int count() {
        return count;
    }
}
